package com.jessehu.xutilstest;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jessehu.xutilstest.bean.DataBean;
import com.jessehu.xutilstest.utils.DebugLog;
import com.jessehu.xutilstest.utils.MyToast;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.util.List;

public class ImageLoaderActivity extends AppCompatActivity {

    private ImageLoaderActivity TAG;
    private ListView mListView;
    private ImageOptions options = new ImageOptions.Builder()
            //设置图片大小,设置图片大小时ImageView的大小必须定义为wrap_content
            .setSize(DensityUtil.dip2px(160), DensityUtil.dip2px(90))
            //设置四个角的弧度
            .setRadius(DensityUtil.dip2px(5))
            // 如果ImageView的大小不是定义为wrap_content, 不要crop.
            .setCrop(true) // 很多时候设置了合适的scaleType也不需要它.
            // 加载中或错误图片的ScaleType
            //.setPlaceholderScaleType(ImageView.ScaleType.MATRIX)
            .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
            //加载中显示的图片
            .setLoadingDrawableId(R.mipmap.ic_launcher)
            //加载失败显示的图片
            .setFailureDrawableId(R.mipmap.ic_launcher)
            //设置使用缓存
            .setUseMemCache(true)
            //设置支持gif
            .setIgnoreGif(false)
            //设置显示圆形图片，设置圆形图片时ImageView的大小必须定义为wrap_content
            //.setCircular(true)
            .build();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_loader);
        TAG = this;
        mListView = (ListView) findViewById(R.id.lv_image_loader);
        loadData();
    }

    //获取数据
    private void loadData() {
        String dataUrl = "http://www.imooc.com/api/teacher?type=4&num=30";
        RequestParams params = new RequestParams(dataUrl);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                List<DataBean> list = getJson(result);
                MyAdapter adapter = new MyAdapter(TAG, list);
                mListView.setAdapter(adapter);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //解析json
    private List<DataBean> getJson(String result) {
        List<DataBean> dataBeen = null;
        if (result != null) {
            JSONObject jsonObject = JSON.parseObject(result);
            String data = jsonObject.getString("data");
            dataBeen = JSON.parseArray(data, DataBean.class);
        }
        return dataBeen;
    }

    private class MyAdapter extends BaseAdapter {

        private List<DataBean> mList;
        private LayoutInflater inflater;

        public MyAdapter(Context context, List<DataBean> list) {
            this.mList = list;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_mlist, null);
                viewHolder = new ViewHolder();
                viewHolder.icon = (ImageView) convertView.findViewById(R.id.iv_item_image_icon);
                viewHolder.title = (TextView) convertView.findViewById(R.id.tv_item_image_title);
                viewHolder.desc = (TextView) convertView.findViewById(R.id.tv_item_image_desc);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            //不设置CacheCallback，如果ImageOption设置了setUseMemCache(true)，则默认加载
            x.image().bind(viewHolder.icon, mList.get(position).getPicSmall(), options, new Callback
                    .CacheCallback<Drawable>() {

                @Override
                public boolean onCache(Drawable result) {
                    //是否信任使用缓存，true使用，每次优先读取缓存；false不使用,每次都会重新获取
                    return true;
                }

                @Override
                public void onSuccess(Drawable result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

            viewHolder.title.setText(mList.get(position).getName());
            viewHolder.desc.setText(mList.get(position).getDescription());
            return convertView;
        }

        class ViewHolder {
            public ImageView icon;
            public TextView title, desc;
        }
    }

    @Override
    protected void onDestroy() {
        //获取缓存文件夹已使用的大小
        File absoluteFile = this.getExternalCacheDir().getAbsoluteFile();
        MyToast.showToast(this, getFolderSize(absoluteFile)+"");

        //清理图片缓存
        x.image().clearCacheFiles();
        x.image().clearMemCache();
        super.onDestroy();
    }
    //获取文件夹大小
    private long getFolderSize(File file) {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }
}
